define(function (require, exports, module) {
    'use strict';
    var $ = require('jquery'),
        _ = require('underscore'),
        Backbone = require('backbone'),
        notify = require('js/utils/notify'),
        models = require('js/apps/op/models'),
        utils = require('js/utils/tools'),
        app = Backbone.history;
    require('jquery-ui');

    var CouponTemplateListView = Backbone.View.extend({
        tagName: "div",
        events: {
            'click a.onClickDelete': 'toDelete',
            'click #search': 'doSearch',
        },

        initialize: function (options) {
            this.options = options;
            this.collection = new models.CouponTemplateCollection();
            this.collection.bind('change reset remove', this.renderWithData, this);
        },
        render: function () {
            this.$el.html("");
            $(window).scrollTop(0);
            return this;
        },
        doSearch: function () {
            var options = utils.getAllInput("#sidebar_right", true),
                searched = utils.getAllInput('#sidebar_right');
            if (searched.id) {
                var id = Number(searched.id);
                if (isNaN(id)) {
                    options.title = {
                        '$like': searched.id
                    };
                    delete options.id;
                }
            }
            utils.saveSearched('op/coupon_tmpl', searched);
            app.navigate(utils.composeQueryString('#op/coupon_tmpl/', options), {
                trigger: true
            });
        },
        toDelete: function (e) {
            utils.deleteItem(e, this.collection);
        },
        renderWithData: function () {
            this.$el.html(this.template({
                items: this.collection.toJSON(),
                searched: utils.getSearched('op/coupon_tmpl')
            }));
            var that = this;
            utils.renderTable('main-list', {
                $orderby: that.options.$orderby || 'id',
                sortCallback: function (field) {
                    that.options.$orderby = field;
                    that.options.$page = 1;
                    var newUrl = utils.composeQueryString('#op/coupon_tmpl/', that.options);
                    app.navigate(newUrl, {
                        trigger: true
                    });
                }
            });
            utils.getPaginator(that.options, this.collection.total, '#op/coupon_tmpl/');

            return this;
        },
        load: function () {
            this.collection.fetch({
                reset: true,
                data: this.options,
                error: function (c, r, o) {
                    notify.notifyResp(r);
                    $('#content').append('<h4 class="text-muted">无数据</h4>');
                },
            });
        }
    });
    exports.List = Backbone.View.extend({
        el: "#content_wrapper",
        template: "op/CouponTemplateList.html",

        initialize: function (options) {
            this.options = options;
        },
        render: function () {
            var view = new CouponTemplateListView(this.options);
            view.template = this.template;

            this.$el.empty();
            this.$el.append(view.render().el);
            view.load();

            return this;
        }
    });
    var CouponTemplateDetailView = Backbone.View.extend({
            tagName: "div",
            className: "panel-body pn",
            events: {
                'click #couponTemplateSave': 'toSaveOrCreate'
            },
            initialize: function (options) {
                this.model = new models.CouponTemplate();
                this.allCategories = new models.CategoryCollection();
                if (options.id) {
                    this.model.set('id', options.id);
                }
                this.model.bind('change reset', this.renderWithData, this);
                this.allCategories.bind('reset', this.renderWithData, this);
            },
            render: function () {
                this.$el.html("");
                $(window).scrollTop(0);
                return this;
            },
            toSaveOrCreate: function (e) {
                e.preventDefault();
                if (!utils.simpleCheck("#coupon-template-form")) {
                    notify.error('错误', "输入错误，请检验");
                    return;
                }
                var attrs = {
                    'title': $('#inputTitle').val(),
                    'desc': $("#inputDesc").val(),
                    'coupon_type': parseInt($('#inputCouponType').val()),
                    'price': parseFloat($('#inputPrice').val()),
                    'valid_ts': parseInt($('#inputValidTs').val(), 10),
                    'activity_type': parseInt($('#inputActivityType').val()),
                    'scope_all': parseInt($('#inputScopeAll').val()),
                    'cmd': $('#inputCmd').val(),
                    'remark': $('#inputRemark').val(),
                    'bet_type': $('#betType').val(),
                };
                attrs.activity_categories = ($('#inputActivityCategories').val() || []).join(',');
                if(attrs.coupon_type == 2){
                    attrs.condition_price = parseInt(
                        $('#inputConditionPrice').val());
                }
                attrs.valid_ts = attrs.valid_ts * 24 * 60 * 60;
                this.model.save(attrs, {
                    patch: true,
                    success: function (model, response) {
                        notify.success('提示', '保存成功！');
                        setTimeout(function () {
                            history.back();
                        }, 500);
                    },
                    error: function (model, response) {
                        notify.notifyResp(response);
                    }
                });

                return false;
            },
            renderWithData: function () {
                var data = this.model.toJSON();
                data['allCategories'] = this.allCategories.toJSON();
                this.$el.html(this.template(data));
                utils.multiselect('.multiselect');
                utils.getValidator('#coupon-template-form');
                return this;
            },
            load: function () {
                if (this.model.id) {
                    this.model.fetch({
                        reset: true
                    });
                } else {
                    this.renderWithData();
                }
                this.allCategories.fetch({
                    reset: true
                });
            }
    });
    exports.Detail = Backbone.View.extend({
        el: "#content_wrapper",
        template: "op/CouponTemplateDetail.html",

        initialize: function (options) {
            this.options = options;
        },
        
        events: {
            "change #inputActivityType": "changeInputActivityType"
        },

        changeInputActivityType: function(e){
            var lottery = e.currentTarget.value;
            var bet_type = window.BET_TYPE[lottery];
            var betTypeSelect = $('#betType');
            betTypeSelect.find('option').remove();
            var k;
            betTypeSelect.append('<option value="0">无</option>');
            for(k in bet_type){
                betTypeSelect.append('<option value='+ k +'>'+bet_type[k]+'</option>');}
        },
        render: function () {
            var view = new CouponTemplateDetailView(this.options);
            view.template = this.template;

            this.$el.empty();
            this.$el.append(view.render().el);
            view.load();

            return this;
        }
    });

});